﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using AvansRS.Domain;
using AvansRS.Domain.DataInterface;
using StructureMap;

namespace AvansRS.Web.Service
{
    public class AuthorizationService
    {
        private IPersonRepository _repository;
        private IDictionary<PersonType, IList<string>> _allowedActions; 

        public AuthorizationService()
        {
            _repository = ObjectFactory.GetInstance<IPersonRepository>();

            IList<string> allowedActionsForDocent = new List<string>();
            allowedActionsForDocent.Add("Account");
            allowedActionsForDocent.Add("Event");
            allowedActionsForDocent.Add("EventDate");
            allowedActionsForDocent.Add("Group");
            allowedActionsForDocent.Add("Home");
            allowedActionsForDocent.Add("Rooster");
            allowedActionsForDocent.Add("Upload");
            allowedActionsForDocent.Add("User");

            IList<string> allowedActionsForStudent = new List<string>();
            allowedActionsForStudent.Add("Home");
            allowedActionsForStudent.Add("Register");

            IList<string> allowedActionsForNone = new List<string>();

            _allowedActions = new Dictionary<PersonType, IList<string>>();
            _allowedActions.Add(PersonType.Docent, allowedActionsForDocent);
            _allowedActions.Add(PersonType.Student, allowedActionsForStudent);
            _allowedActions.Add(PersonType.None, allowedActionsForNone);
        }

        public void Authorize(string username, string action)
        {
            Person person = _repository.FindByAccountUsername(username);

            PersonType personType = person.Type;

            IList<string> allowedActions = _allowedActions[personType];

            bool contains = allowedActions.Contains(action);

            if (!contains)
                throw new NotAuthorizedException(username, personType.ToString(), action);
        }
    }
}
